package com.pureut.quality.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.api.FeignProductionService;
import com.pureut.production.api.domain.vo.LineStockVo;
import com.pureut.production.api.domain.vo.UpdateLineStockStatusVo;
import com.pureut.quality.domain.QualityProductionFreeze;
import com.pureut.quality.domain.dto.LineStockDto;
import com.pureut.quality.domain.dto.QualityProductionFreezeDto;
import com.pureut.quality.domain.dto.WmsStockInfoDto;
import com.pureut.quality.domain.vo.QualityProductionFreezeVo;
import com.pureut.quality.domain.vo.ThawVo;
import com.pureut.quality.mapper.QualityProductionFreezeMapper;
import com.pureut.quality.service.QualityProductionFreezeService;
import com.pureut.system.api.StorageFegin;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.QualityFreezeVo;
import com.pureut.system.api.vo.WarehouseStatusUpdateVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/***
 * 生产冻结表实现层
 * Author:C
 * Date:2023/02/07 14:05
 * @DESC
 */
@Service
public class QualityProductionFreezeServiceImpl extends ServiceImpl<QualityProductionFreezeMapper, QualityProductionFreeze> implements QualityProductionFreezeService {

    @Resource
    QualityProductionFreezeMapper qualityProductionFreezeMapper;

    @Resource
    StorageFegin storageFegin;

    @Resource
    FeignProductionService feignProductionService;

    /**
     * 生产冻结列表
     *
     * @param qualityProductionFreezeVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<QualityProductionFreezeDto> getFreezeList(QualityProductionFreezeVo qualityProductionFreezeVo) {

        //生产冻结状态
        List<SysDictData> freezingStatusArray = DictUtils.getDictCache("freezing_status");
        Map<String, String> freezingStatusMap = freezingStatusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //物料等级
        List<SysDictData> gradeArray = DictUtils.getDictCache("freezing_grade");
        Map<String, String> gradeMap = gradeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<QualityProductionFreezeDto> list = qualityProductionFreezeMapper.getList(qualityProductionFreezeVo);

        for (QualityProductionFreezeDto entity : list) {
            //生产冻结状态
            entity.setStatusDict(freezingStatusMap.get(entity.getStatus()));
            //物料等级
            entity.setMaterialGradeDict(gradeMap.get(entity.getMaterialGrade()));
        }
        return list;
    }

    /**
     * 冻结查询
     *
     * @param qualityProductionFreezeVo
     * @return
     */
    @Override
    public List<QualityProductionFreezeDto> getFreeze(QualityProductionFreezeVo qualityProductionFreezeVo) {
        List<QualityProductionFreezeDto> qualityProductionFreezeList = new ArrayList<>();
        QualityFreezeVo qualityFreezeVo = new QualityFreezeVo();
//        BeanUtils.copyProperties(qualityProductionFreezeVo, qualityFreezeVo);
        qualityFreezeVo.setStartTime(qualityProductionFreezeVo.getWsiProducedDateStart());
        qualityFreezeVo.setEndTime(qualityProductionFreezeVo.getWsiProducedDateEnd());
        qualityFreezeVo.setLineCode(qualityProductionFreezeVo.getProductionLine());
        String materialCode = qualityProductionFreezeVo.getWsiMaterialCode();
        qualityFreezeVo.setWsiMaterialCode(qualityProductionFreezeVo.getWsiMaterialCode());
        qualityFreezeVo.setWsiConnectNum(qualityProductionFreezeVo.getOrderNo());
        String wsiMaterialNumber = qualityProductionFreezeVo.getWsiMaterialNumber();
        qualityFreezeVo.setWsiMaterialNumber(qualityProductionFreezeVo.getWsiMaterialNumber());
        //查询仓库数据
        AjaxResult freezeStockList = storageFegin.getFreezeStockList(qualityFreezeVo);
        List<WmsStockInfoDto> data = JSON.parseArray(JSON.toJSONString(freezeStockList.get("data")), WmsStockInfoDto.class);
        if (data.size() > 0) {
            for (WmsStockInfoDto entity : data) {
                QualityProductionFreezeDto qualityProductionFreezeDto = new QualityProductionFreezeDto();
                qualityProductionFreezeDto
                        .setId(entity.getId())
                        .setOrderNo(entity.getWsiConnectNum())
                        .setMaterialGrade(entity.getWsiMaterialGrade())
                        .setProductNumber(entity.getWsiMaterialNumber())
                        .setMaterialCode(entity.getWsiMaterialCode())
                        .setMaterialName(entity.getWsiMaterialName())
                        .setMaterialSpec(entity.getWsiMaterialSpec())
                        .setNetWeight(String.valueOf(entity.getWsiNetWeight()))
                        .setWarehouseCategory(1);
                qualityProductionFreezeList.add(qualityProductionFreezeDto);
            }
        }

        // 查询线边仓数据
        LineStockVo lineStockVo = new LineStockVo();
        lineStockVo.setStartTime(qualityProductionFreezeVo.getWsiProducedDateStart());
        lineStockVo.setEndTime(qualityProductionFreezeVo.getWsiProducedDateEnd());
        lineStockVo.setLineCode(qualityProductionFreezeVo.getProductionLine());
        String wsiMaterialCode = qualityProductionFreezeVo.getWsiMaterialCode();
        lineStockVo.setMaterialCode(qualityProductionFreezeVo.getWsiMaterialCode());
        lineStockVo.setStockAlCode(qualityProductionFreezeVo.getOrderNo());
        lineStockVo.setMaterialNumber(qualityProductionFreezeVo.getWsiMaterialNumber());
        AjaxResult lineStockList = feignProductionService.getLineStockList(lineStockVo);
        List<LineStockDto> lineStockData = JSON.parseArray(JSON.toJSONString(lineStockList.get("data")), LineStockDto.class);
        if (lineStockData.size() > 0) {
            for (LineStockDto entity : lineStockData) {
                QualityProductionFreezeDto qualityProductionFreezeDto = new QualityProductionFreezeDto();
                qualityProductionFreezeDto
                        .setId(entity.getStockId())
                        .setOrderNo(entity.getStockAlCode())
                        .setMaterialGrade(String.valueOf(entity.getMaterialGrade()))
                        .setProductNumber(entity.getMaterialNumber())
                        .setMaterialCode(entity.getMaterialCode())
                        .setMaterialName(entity.getMaterialName())
                        .setMaterialSpec(entity.getMaterialSpec())
                        .setNetWeight(String.valueOf(entity.getNetWeight()))
                        .setProductionLine(entity.getLineCode())
                        .setWarehouseCategory(2);
                qualityProductionFreezeList.add(qualityProductionFreezeDto);
            }
        }
        return qualityProductionFreezeList;
    }

    /**
     * 冻结
     *
     * @param qualityProductionFreezeVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean freeze(QualityProductionFreezeVo qualityProductionFreezeVo) {

        List<com.pureut.system.api.dto.QualityProductionFreezeDto> materialList = qualityProductionFreezeVo.getMaterialList();
        if (materialList.size() < 1) {
            throw new GlobalException("请至少选择一条数据!");
        }
        List<QualityProductionFreeze> qualityProductionFreezeList = new ArrayList<>();

        //修改对应仓库的数据状态
        List<com.pureut.system.api.dto.QualityProductionFreezeDto> collect = materialList.stream().filter(entity -> entity.getWarehouseCategory() == 1).collect(Collectors.toList());
        if (collect.size() > 0) {
//            List<Long> warehouseIds = new ArrayList<>();
//            for (com.pureut.system.api.dto.QualityProductionFreezeDto entity : collect) {
//                warehouseIds.add(entity.getId());
//            }
            WarehouseStatusUpdateVo warehouseStatusUpdateVo = new WarehouseStatusUpdateVo();
//            List<QualityProductionFreeze> qualityProductionFreezes = qualityProductionFreezeMapper.selectList(new QueryWrapper<QualityProductionFreeze>().lambda().in(QualityProductionFreeze::getWarehouseId, warehouseIds));
            List<String> materialNumberList = new ArrayList<>();
            for (com.pureut.system.api.dto.QualityProductionFreezeDto entity : materialList) {
                materialNumberList.add(entity.getProductNumber());
            }
//            warehouseStatusUpdateVo.setIds(warehouseIds);
            warehouseStatusUpdateVo.setMaterialNumberList(materialNumberList);
            warehouseStatusUpdateVo.setFreeValue("1");
            storageFegin.getUpdate(warehouseStatusUpdateVo);
        }
        //修改对应线边仓的数据状态
        List<com.pureut.system.api.dto.QualityProductionFreezeDto> collectLineStock = materialList.stream().filter(entity -> entity.getWarehouseCategory() == 2).collect(Collectors.toList());
        if (collectLineStock.size() > 0) {
//            List<Long> lineStockIds = new ArrayList<>();
//            for (com.pureut.system.api.dto.QualityProductionFreezeDto entity : collectLineStock) {
//                lineStockIds.add(entity.getId());
//            }
            List<String> materialNumberList = new ArrayList<>();
            for (com.pureut.system.api.dto.QualityProductionFreezeDto entity : materialList) {
                materialNumberList.add(entity.getProductNumber());
            }
            UpdateLineStockStatusVo updateLineStockStatusVo = new UpdateLineStockStatusVo();
//            List<QualityProductionFreeze> qualityProductionFreezes = qualityProductionFreezeMapper.selectList(new QueryWrapper<QualityProductionFreeze>().lambda().in(QualityProductionFreeze::getId, lineStockIds));

//            for (QualityProductionFreeze entity : qualityProductionFreezes) {
//                materialNumberList.add(entity.getProductNumber());
//            }
//            warehouseStatusUpdateVo.setIds(warehouseIds);
            updateLineStockStatusVo.setMaterialNumberList(materialNumberList);
            updateLineStockStatusVo.setFreeValue(1);
            feignProductionService.updateLineStockStatus(updateLineStockStatusVo);
        }
        //新增生产冻结数据
        for (com.pureut.system.api.dto.QualityProductionFreezeDto entityFreeze : materialList) {
            QualityProductionFreeze qualityProductionFreeze = new QualityProductionFreeze();
            if (entityFreeze.getWarehouseCategory() == 1) {
                qualityProductionFreeze.setStatus(1)
                        .setMaterialGrade(1)
                        .setMaterialCode(entityFreeze.getMaterialCode())
                        .setOrderNo(entityFreeze.getOrderNo())
                        .setFrozenBy(SecurityUtils.getUsername())
                        .setFrozenTime(new Date())
                        .setFrozenReason(qualityProductionFreezeVo.getFrozenReason())
                        .setProductNumber(entityFreeze.getProductNumber())
                        .setCreateTime(new Date())
                        .setDeptId(SecurityUtils.getDeptId())
                        .setWarehouseCategory(1)
                        .setWarehouseId(entityFreeze.getId())
                        .setNetWeight(entityFreeze.getNetWeight())
                        .setProductionLine(entityFreeze.getProductionLine());
            } else {
                qualityProductionFreeze.setStatus(1)
                        .setMaterialGrade(1)
                        .setMaterialCode(entityFreeze.getMaterialCode())
                        .setOrderNo(entityFreeze.getOrderNo())
                        .setFrozenBy(SecurityUtils.getUsername())
                        .setFrozenTime(new Date())
                        .setFrozenReason(qualityProductionFreezeVo.getFrozenReason())
                        .setProductNumber(entityFreeze.getProductNumber())
                        .setCreateTime(new Date())
                        .setDeptId(SecurityUtils.getDeptId())
                        .setWarehouseCategory(2)
                        .setWarehouseId(entityFreeze.getId())
                        .setNetWeight(entityFreeze.getNetWeight())
                        .setProductionLine(entityFreeze.getProductionLine());
            }
            qualityProductionFreezeList.add(qualityProductionFreeze);
        }
        return saveBatch(qualityProductionFreezeList);
    }

    /**
     * 解冻
     *
     * @param thawVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean thaw(ThawVo thawVo) {

        List<String> idList = Arrays.asList(thawVo.getIds().split(","));
        if (idList.size() < 1) {
            throw new GlobalException("请至少勾选一条数据!");
        }
        List<QualityProductionFreeze> qualityProductionFreezeList = qualityProductionFreezeMapper.selectList(new QueryWrapper<QualityProductionFreeze>().lambda().in(QualityProductionFreeze::getId, idList));
        List<Long> warehouseIds = new ArrayList<>();
        List<Long> lineStockIds = new ArrayList<>();
        for (QualityProductionFreeze entity : qualityProductionFreezeList) {
            if (entity.getStatus() == 1) {
                entity.setStatus(2);
                entity.setThawReason(thawVo.getThawReason());
                entity.setThawBy(SecurityUtils.getUsername());
                entity.setThawTime(new Date());
                if (entity.getWarehouseCategory() == 1) {
                    warehouseIds.add(entity.getWarehouseId());
                } else {
                    //线边仓id集合
                    lineStockIds.add(entity.getWarehouseId());
                }
            } else {
                throw new GlobalException("只能对冻结状态的物料进行解冻操作");
            }
        }
        //修改仓库中的冻结状态为关闭
        if (warehouseIds.size() > 0) {
            WarehouseStatusUpdateVo warehouseStatusUpdateVo = new WarehouseStatusUpdateVo();
            List<QualityProductionFreeze> qualityProductionFreezes = qualityProductionFreezeMapper.selectList(new QueryWrapper<QualityProductionFreeze>().lambda().in(QualityProductionFreeze::getWarehouseId, warehouseIds));
            List<String> materialNumberList = new ArrayList<>();
            for (QualityProductionFreeze entity : qualityProductionFreezes) {
                materialNumberList.add(entity.getProductNumber());
            }
//            warehouseStatusUpdateVo.setIds(warehouseIds);
            warehouseStatusUpdateVo.setMaterialNumberList(materialNumberList);
            warehouseStatusUpdateVo.setFreeValue("2");
            storageFegin.getUpdate(warehouseStatusUpdateVo);
        }
        if (lineStockIds.size() > 0) {
            //修改线边仓数据冻结状态为未冻结
            UpdateLineStockStatusVo updateLineStockStatusVo = new UpdateLineStockStatusVo();
            List<QualityProductionFreeze> qualityProductionFreezes = qualityProductionFreezeMapper.selectList(new QueryWrapper<QualityProductionFreeze>().lambda().in(QualityProductionFreeze::getWarehouseId, lineStockIds));
            List<String> materialNumberList = new ArrayList<>();
            for (QualityProductionFreeze entity : qualityProductionFreezes) {
                materialNumberList.add(entity.getProductNumber());
            }
//            updateLineStockStatusVo.setIds(lineStockIds);
            updateLineStockStatusVo.setMaterialNumberList(materialNumberList);
            updateLineStockStatusVo.setFreeValue(2);
            feignProductionService.updateLineStockStatus(updateLineStockStatusVo);
        }
        return updateBatchById(qualityProductionFreezeList);

    }

    /**
     * 查看
     *
     * @param ids
     * @return
     */
    @Override
    public List<QualityProductionFreezeDto> getView(String ids) {

        List<String> idList = Arrays.asList(ids.split(","));
        List<QualityProductionFreezeDto> viewById = qualityProductionFreezeMapper.getViewById(idList);

        //生产冻结状态
        List<SysDictData> freezingStatusArray = DictUtils.getDictCache("freezing_status");
        Map<String, String> freezingStatusMap = freezingStatusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //物料等级
        List<SysDictData> gradeArray = DictUtils.getDictCache("freezing_grade");
        Map<String, String> gradeMap = gradeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (QualityProductionFreezeDto entity : viewById) {
            entity.setStatusDict(freezingStatusMap.get(entity.getStatus()));

            entity.setMaterialGradeDict(gradeMap.get(entity.getMaterialGrade()));
        }
        return viewById;
    }

    /**
     * 品质处理
     *
     * @param thawVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean qualityTreatment(ThawVo thawVo) {

        List<String> idList = Arrays.asList(thawVo.getIds().split(","));
        if (idList.size() < 1) {
            throw new GlobalException("请至少勾选一条数据!");
        }
        List<QualityProductionFreeze> qualityProductionFreezeList = qualityProductionFreezeMapper.selectList(new QueryWrapper<QualityProductionFreeze>().lambda().in(QualityProductionFreeze::getId, idList));
        List<Long> warehouseIds = new ArrayList<>();
        List<Long> lineStockIds = new ArrayList<>();
        for (QualityProductionFreeze entity : qualityProductionFreezeList) {
            if (entity.getStatus() == 1) {
                //2.处理后，对应物料的物料等级为处理结果，状态更新为“解冻”
                entity.setMaterialGrade(thawVo.getMaterialGrade());
                entity.setStatus(2);
                if (entity.getWarehouseCategory() == 1) {
                    warehouseIds.add(entity.getWarehouseId());
                } else {
                    //线边仓id集合
                    lineStockIds.add(entity.getWarehouseId());
                }
            } else {
                throw new GlobalException("只能对冻结状态的物料进行品质处理操作");
            }
        }
        //同时库存（仓库+线边）中的冻结标识关闭，库存中物料等级更新为处理结果
        //修改仓库中的冻结状态为关闭,修改仓库中的物料等级
        if (warehouseIds.size() > 0) {
            WarehouseStatusUpdateVo warehouseStatusUpdateVo = new WarehouseStatusUpdateVo();
//            List<QualityProductionFreeze> qualityProductionFreezes = qualityProductionFreezeMapper.selectList(new QueryWrapper<QualityProductionFreeze>().lambda().in(QualityProductionFreeze::getId, warehouseIds));
            List<String> materialNumberList = new ArrayList<>();
            for (QualityProductionFreeze entity : qualityProductionFreezeList) {
                materialNumberList.add(entity.getProductNumber());
            }
//            warehouseStatusUpdateVo.setIds(warehouseIds);
            warehouseStatusUpdateVo.setMaterialNumberList(materialNumberList);
            warehouseStatusUpdateVo.setStatusValue(2);
            warehouseStatusUpdateVo.setMaterialGradeValue(thawVo.getMaterialGrade());
            storageFegin.getUpdate(warehouseStatusUpdateVo);
        }
        if (lineStockIds.size() > 0) {
            //修改线边仓数据冻结状态为未冻结
            UpdateLineStockStatusVo updateLineStockStatusVo = new UpdateLineStockStatusVo();
            List<QualityProductionFreeze> qualityProductionFreezes = qualityProductionFreezeMapper.selectList(new QueryWrapper<QualityProductionFreeze>().lambda().in(QualityProductionFreeze::getWarehouseId, lineStockIds));
            List<String> materialNumberList = new ArrayList<>();
            for (QualityProductionFreeze entity : qualityProductionFreezes) {
                materialNumberList.add(entity.getProductNumber());
            }
//            updateLineStockStatusVo.setIds(lineStockIds);
            updateLineStockStatusVo.setFreeValue(2);
            updateLineStockStatusVo.setMaterialNumberList(materialNumberList);
            updateLineStockStatusVo.setMaterialGradeValue(thawVo.getMaterialGrade());
            feignProductionService.updateLineStockStatus(updateLineStockStatusVo);
        }
        return updateBatchById(qualityProductionFreezeList);
    }


    /**
     * 小卷打包数据新增（fegin调用）
     *
     * @param qualityProductionFreezeVo
     * @return
     */
    @Override
    public boolean smallRollAdd(QualityProductionFreezeVo qualityProductionFreezeVo) {

        QualityProductionFreeze qualityProductionFreeze = new QualityProductionFreeze();
        qualityProductionFreeze.setStatus(1)
                .setMaterialGrade(1)
                .setMaterialCode(qualityProductionFreezeVo.getMaterialCode())
                .setProductionLine(qualityProductionFreezeVo.getProductionLine())
                .setOrderNo(qualityProductionFreezeVo.getOrderNo())
                .setFrozenBy(SecurityUtils.getUsername())
                .setFrozenTime(new Date())
                .setProductNumber(qualityProductionFreezeVo.getProductNumber())
                .setCreateTime(new Date())
                .setDeptId(SecurityUtils.getDeptId());
        return save(qualityProductionFreeze);
    }
}
